<template>
  <div>
    <r-search
      ref="search"
      :searchData="searchData"
      :searchForm="searchForm"
      :searchHandle="searchHandle"
    />
    <!-- AddAgent优惠活动 -->
    <div>
      <el-dialog
        width="35%"
        title="AddAgent优惠活动"
        :visible.sync="dialogFormVisible"
      >
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Agent" :label-width="formLabelWidth">
            <el-select
              placeholder="Please SelectAgent"
              :clearable="true"
              v-model="agentValue"
              style="width:250px"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="优惠活动" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select活动"
              :clearable="true"
              v-model="agentIdValue"
              multiple
              style="width:250px"
            >
              <el-option
                v-for="item in agentIdArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div>Agent已经Add的优惠活动：</div>
        <el-table :data="inquireAgentData" style="text-align:center">
          <el-table-column
            property="id"
            label="Coupon活动id"
            width="150"
            align="center"
          />
          <el-table-column
            property="activityName"
            label="CouponName"
            width="150"
            align="center"
          />
          <el-table-column
            property="activityDesc"
            label="Brief Introduction"
            width="150"
            align="center"
          />
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
        </div>
      </el-dialog>
    </div>

    <r-table
      :isSelection="false"
      :isHandle="true"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="pagination"
      :loading="tableLoading"
      :tableHandles="tableHandles"
      @refresh="page()"
    />
    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules"
      :formCols="formCols"
      :formHandle="formHandle"
      :formData="formData"
      ref="elForm"
      :inline="false"
      dialogWidth="650px"
    />
  </div>
</template>

<script>
export default {
  data() {
    var checkToFixedTwo = (rule, value, callback) => {
      const reg = /[^\d]/g;
      if (!reg.test(value)) {
        callback();
      } else {
        return callback(new Error("Please InputInteger Number"));
      }
    };
    return {
      changePwdData: {
        show: false
      },
      tableLoading: false,
      searchData: {
        couponType: "",
        isOpen: ""
      },
      searchForm: [
        {
          type: "select",
          placeholder: "Coupon Type",
          prop: "couponType",
          width: 240,
          options: [
            { label: "Recharge Coupon", value: 0 },
            { label: "Temporary Storage Voucher", value: 1 },
            { label: "Voucher", value: 2 },
            { label: "Try Out Coupon", value: 3 },
            { label: "Package Deduction Coupon", value: 4 }
          ]
        },
        {
          type: "select",
          placeholder: "Whether Forbidden",
          prop: "isOpen",
          width: 270,
          options: [
            { label: "Forbidden", value: 0 },
            { label: "Normal", value: 1 }
          ]
        }
        // { type: "select", placeholder: "是否Forbidden", prop: "isOpen", width: 150, options: [{ label: 'Forbidden', value: 0 }, { label: 'Enable', value: 1 }] },
      ],
      searchHandle: [
        {
          label: "Search",
          type: "primary",
          plain: true,
          handle: async e => {
            this.zeroFn();
            let page = {
              pageNum: this.pagination.offset,
              pageSize: this.pagination.limit,
              couponType: this.searchData.couponType,
              isOpen: this.searchData.isOpen
            };
            let res = await this.apis.couponList(page);
            // this.getData()
            this.tableData = res.rows || [];
            this.pagination.total = res.total;
            this.searchData.couponType = "";
            this.searchData.isOpen = "";
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              couponType: "",
              isOpen: ""
            };
            this.zeroFn();
            this.getData();
          }
        }
      ],
      tableHandles: [
        {
          label: "AddCoupon",
          type: "primary",
          plain: true,
          handle: e => {
            this.isNew = true;
            this.elFormVisible();
          },
          disabled: sessionStorage.role == "operator" ? false : true
        }
        // {
        //   label: "AddAgent优惠活动",
        //   type: "success",
        //   plain: true,
        //   // plain: true,
        //   isShow: e => {
        //     return sessionStorage.role == "operator" ? true : false;
        //   },
        //   handle: e => {
        //     this.dialogFormVisible = true;
        //   }
        // }
      ],
      tableData: [{}],
      tableCols: [
        // { label: "Couponid", prop: "id" },
        { label: "Name", prop: "name" },
        { label: "Brief Introduction", prop: "couponDesc" },
        {
          label: "Coupon Money",
          prop: "discount",
          // width: 70,
          formatter: e => (e.couponType !== 1 ? "$" + e.discount : "--")
        },
        {
          label: "Limitation",
          prop: "useCondition",
          formatter: e =>
            e.couponType == 0
              ? "Recharge Satisfy $" +
                e.useCondition +
                "，Gift Balance $" +
                e.discount
              : e.couponType == 2
              ? "Unlimited"
              : e.couponType == 4
              ? "Buy Package Satisfy $" +
                e.useCondition +
                "，Deductible $" +
                e.discount
              : "--"
        },
        {
          label: "Type",
          prop: "couponType",
          formatter: e =>
            e.couponType == 0
              ? "Recharge Coupon"
              : e.couponType == 1
              ? e.holdDays
                ? "Temporary Storage Voucher：" + e.holdDays + "/day"
                : "Temporary Storage Voucher"
              : e.couponType == 2
              ? "Voucher"
              : e.couponType == 3
              ? e.tryDays
                ? "Try Out Coupon：" + e.tryDays + "/day"
                : "Try Out Coupon"
              : e.couponType == 4
              ? "Package Deduction Coupon"
              : "--"
        },
        {
          label: "Whether Forbidden",
          prop: "isOpen",
          // width: 60,
          type: "tag",
          theme: e =>
            e.isOpen == 0 ? "danger" : e.isOpen == 1 ? "primary" : "",
          formatter: e =>
            e.isOpen == 0 ? "Forbidden" : e.isOpen == 1 ? "Enable" : "--"
        },
        {
          label: "Operations",
          type: "button",
          width: 220,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              size: "mini",
              plain: true,
              style: { "margin-bottom": "5px" },
              icon: "el-icon-search",
              handle: row => {
                this.isNew = false;
                this.elFormDetail(row);
              }
            },
            {
              label: "Unlock The Offer",
              type: "success",
              size: "mini",
              plain: true,
              icon: "el-icon-sunny",
              handle: async row => {
                let res = await this.apis.couponStartOrStop(row.id);
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
                this.getData();
              },
              isShow: row => {
                return row.isOpen == 0 ? true : false;
              }
            },
            {
              label: "Delete",
              type: "danger",
              size: "mini",
              plain: true,
              handle: async row => {
                this.$confirm(
                  "This Operations will permanently Delete the activity, whether to continue or not?",
                  "Hint",
                  {
                    confirmButtonText: "Confirm",
                    cancelButtonText: "Cancel",
                    type: "warning"
                  }
                )
                  .then(async () => {
                    let res = await this.apis.couponDelete(row.id);
                    this.$message({
                      type: res.code == 200 ? "success" : "error",
                      message: res.msg
                    });
                    this.getData();
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "Already Cancel Delete"
                    });
                  });
              }
            },
            {
              label: "Stop Offers",
              type: "danger",
              size: "mini",
              icon: "el-icon-moon",
              plain: true,
              handle: async row => {
                let res = await this.apis.couponStartOrStop(row.id);
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
                this.getData();
              },
              isShow: row => {
                return row.isOpen == 1 ? true : false;
              }
            }
          ]
        }
      ],
      pagination: { limit: 10, offset: 1, total: 0 },
      formData: {
        id: "",
        name: "",
        couponDesc: "",
        discount: "",
        useCondition: "",
        couponType: null,
        holdDays: "",
        tryDays: ""
      },
      isNew: true,
      formCols: [
        {
          type: "input",
          label: "Couponid",
          width: 350,
          prop: "id",
          isDisabled: () => (this.isNew ? false : true),
          isShow: () => (!this.isNew ? true : false)
        },
        { type: "input", label: "CouponName", width: 350, prop: "name" },
        {
          type: "input",
          label: "Brief Introduction",
          width: 350,
          prop: "couponDesc"
        },
        {
          type: "select",
          label: "CouponType",
          width: 350,
          prop: "couponType",
          options: [
            { label: "Recharge Coupon", value: 0 },
            { label: "Temporary Storage Voucher", value: 1 },
            { label: "Voucher", value: 2 },
            { label: "Try Out Coupon", value: 3 },
            { label: "Package Deduction Coupon", value: 4 }
          ]
        },
        {
          type: "input",
          label: "Coupon Money",
          width: 350,
          prop: "discount",
          placeholder: "Please Input Coupon Money",
          // remark: "元",
          isShow: () => !this.isTemporary && !this.isTryOut
        },
        {
          type: "input",
          label: "Limitation",
          width: 350,
          prop: "useCondition",
          placeholder:
            "Please Input Money,How much more can you use this Coupon($)",
          // remark: "元",
          isShow: () => this.isCharge
        },
        {
          type: "input",
          label: "Temporary Voucher Storage Duration",
          width: 350,
          prop: "holdDays",
          // remark: "天",
          isShow: () => this.isTemporary
        },
        {
          type: "input",
          label: "Try Out Duration",
          width: 350,
          prop: "tryDays",
          // remark: "天",
          isShow: () => this.isTryOut
        }
      ],
      formRules: {
        name: [{ required: true, message: "Please Enter", trigger: "blur" }],
        couponDesc: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        discount: [
          { required: true, message: "Please Enter", trigger: "blur" }
          // { validator: checkToFixedTwo, trigger: "blur" }
        ],
        useCondition: [
          { required: true, message: "Please Enter", trigger: "blur" }
          // { validator: checkToFixedTwo, trigger: "blur" }
        ],
        couponType: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        holdDays: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        tryDays: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      formHandle: [
        {
          label: "Cancel",
          icon: "el-icon-circle-close",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "primary",
          icon: "el-icon-circle-plus-outline",
          handle: e => this.elFormSubmit()
        }
      ],
      agentArr: [],
      isCharge: false,
      isTemporary: false,
      isTryOut: false,
      agentIdArr: [],
      dialogFormVisible: false,
      formLabelWidth: "80px",
      agentValue: "",
      agentIdValue: [],
      inquireAgentData: []
    };
  },
  watch: {
    "formData.couponType": {
      handler(newValue, oldValue) {
        console.log(222222, newValue, oldValue);
        this.isFn(newValue);
      },
      deep: true // 深度监听
    },
    dialogFormVisible: {
      handler(newValue, oldValue) {
        if (!newValue && oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        } else if (newValue && !oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        // console.log('新', newValue, '---旧', oldValue)
        if (newValue) {
          this.inquireAgentFn(newValue);
          this.yesAgentFn(newValue);
        } else {
          return;
        }
      },
      deep: true // 深度监听
    }
  },
  created() {},
  async mounted() {
    this.getData();
    // 拿到Agentid列表
    let param = {
      pageNum: this.pagination.offset,
      pageSize: this.pagination.limit
    };
    let res = await this.apis.agent_list(param);
    let arr = res.rows;
    this.agentArr = [];
    arr.forEach(i => {
      let testAgentArr = {
        id: i.id,
        name: i.name
      };
      this.agentArr.push(testAgentArr);
    });
  },
  methods: {
    zeroFn() {
      this.pagination.limit = 10;
      this.pagination.offset = 1;
      this.pagination.total = 0;
    },
    // 获取Agent未参加的活动
    async inquireAgentFn(id) {
      this.agentIdArr = [];
      let res = await this.apis.activityListNotActivityByAgent(id);
      let arr = res.data || [];
      arr.forEach(i => {
        let testAgentArr = {
          id: i.id,
          name: i.activityName
        };
        this.agentIdArr.push(testAgentArr);
      });
    },
    // 获取Agent已经参加的活动
    async yesAgentFn(id) {
      let res = await this.apis.activityList({
        pageNum: this.pagination.offset,
        pageSize: this.pagination.limit,
        agentId: id
      });
      this.inquireAgentData = res.rows || [];
    },
    async affirmAgentFn() {
      if (!this.agentValue) {
        this.$message({
          message: "Please SelectAgent",
          type: "error"
        });
        return false;
      }
      if (this.agentIdValue.length === 0) {
        this.$message({
          message: "Please Select Activity",
          type: "error"
        });
        return false;
      }
      this.dialogFormVisible = false;
      if (this.agentValue && this.agentIdValue.length !== 0) {
        let params = {
          agentId: this.agentValue,
          couponIds: this.agentIdValue
        };
        let res = await this.apis.couponAddOrUpdateAgentCoupon(params);

        this.$message({
          type: res.code == 200 ? "success" : "error",
          message: res.msg
        });
      }
    },
    isShow_() {
      if (this.formData.id) {
        this.formRules.password[0].required = false;
        return true;
      } else {
        this.formRules.password[0].required = true;
        return true;
      }
    },
    changePwdCall() {
      this.changePwdData.show = false;
    },
    del(row) {
      this.$confirm("Confirm Delete?", "Hint", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      })
        .then(async () => {
          var res = await this.apis.user_delete({
            userId: row.userId
          });
          this.$message({
            type: "success",
            message: "Delete Success!"
          });
          this.getData();
        })
        .catch(() => {});
    },
    async getData() {
      let res = await this.apis.couponList({
        pageNum: this.pagination.offset,
        pageSize: this.pagination.limit
      });
      this.tableData = res.rows || [];
      this.pagination.total = res.total;
      // 拿到Coupon活动数组
      if (this.tableData) {
        this.agentIdArr = [];
        this.tableData.forEach(i => {
          let testAgentArr;
          if (i.status !== 1) {
            if (!i.holdDays) {
              i.holdDays = 0;
            }
            testAgentArr = {
              id: i.id,
              name:
                i.couponType == 0
                  ? "Recharge Coupon：" +
                    "Satisfy" +
                    i.useCondition +
                    "Usable $" +
                    i.discount
                  : i.couponType == 1
                  ? "Temporary Storage Voucher：" + "Add" + i.holdDays + "/day"
                  : i.couponType == 4
                  ? "Package Deduction Coupon：" +
                    "Satisfy" +
                    i.useCondition +
                    "Usable $" +
                    i.discount
                  : "Voucher：" + "Money $" + i.discount
            };
            this.agentIdArr.push(testAgentArr);
          } else {
            return;
          }
        });
      }
    },
    page() {
      this.getData();
    },
    createdAcc() {
      this.elFormVisible();
    },
    isFn(value) {
      if (value === 0) {
        this.isCharge = true;
        this.isTemporary = false;
        this.isTryOut = false;
      } else if (value === 1) {
        this.isCharge = false;
        this.isTemporary = true;
        this.isTryOut = false;
      } else if (value === 3) {
        this.isCharge = false;
        this.isTemporary = false;
        this.isTryOut = true;
      } else if (value === 4) {
        this.isCharge = true;
        this.isTemporary = false;
        this.isTryOut = false;
      } else {
        this.isCharge = false;
        this.isTemporary = false;
        this.isTryOut = false;
      }
    },

    async elFormDetail(row) {
      this.formData.id = row.id;
      this.formData.name = row.name;
      this.formData.couponDesc = row.couponDesc;
      this.formData.discount = row.discount;
      this.formData.useCondition = row.useCondition;
      this.formData.couponType = row.couponType;
      this.formData.holdDays = row.holdDays;
      this.formData.tryDays = row.tryDays;
      this.elFormVisible();
      this.isFn(row.couponType);
    },
    elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.submit();
        }
      });
    },
    async submit() {
      if (!this.formData.holdDays) {
        this.formData.holdDays = "";
      }
      if (!this.formData.tryDays) {
        this.formData.tryDays = "";
      }
      let res;
      if (this.formData.id) {
        res = await this.apis.couponUpdate(this.formData);
      } else {
        delete this.formData.id;
        res = await this.apis.couponInsert(this.formData);
      }
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
      this.elFormVisible();
      this.getData();
    }
  }
};
</script>

<style scoped lang="scss">
.agentIdClass {
  margin-bottom: 20px;
}

.agentIdClass > .el-select {
  margin-left: 8%;
}

.agentIdClass1 > .el-select {
  margin-left: 11%;
}
</style>
